<?php

namespace App\Services\Callback\Payment;

use App\Exceptions\PaymentException;
use App\Helpers\LogHelper;
use App\Models\Applet\Other\PaymentOrderModel;
use Exception;
use Illuminate\Support\Facades\DB;

class WechatPaymentService extends BasePaymentService
{
    /**
     * 回调
     *
     * @param array $params
     * @return void
     * @throws PaymentException
     * @throws Exception
     */
    public function callback(array $params)
    {
        $params = $this->wechatPayApi->decrypt($params);
        LogHelper::info('callback', ['decrypt-params' => $params]);

        $attach = json_decode($params['attach'], true);
        $orderType = $attach['orderType'];
        // 查询订单
        $orderInfo = $this->getOrderService($orderType)->getOrderInfoByOrderMasterNo($params['out_trade_no']);
        if (empty($orderInfo)) {
            throw new PaymentException('订单不存在', PaymentException::CODE_1004);
        }

        // 查询支付订单
        $paymentOrder = $this->getPaymentOrderModel()->getItemByOrderId($orderInfo['order_master_id']);
        if (empty($paymentOrder)) {
            throw new PaymentException('支付订单不存在', PaymentException::CODE_1005);
        }

        DB::transaction(function () use ($orderInfo, $orderType, $params, $paymentOrder) {
            // 更新支付订单
            $this->getPaymentOrderModel()->updateItemById($paymentOrder['id'], [
                'transaction_id' => $params['transaction_id'],
                'pay_status' => PaymentOrderModel::PAY_STATUS_SUCCESS,
                'pay_time' => date('Y-m-d H:i:s'),
            ]);

            // 添加用户认养记录
            if ($orderType == PaymentOrderModel::ORDER_TYPE_SPONSOR) {
                $this->getUserSponsorModel()->addItem([
                    'user_id' => $orderInfo['user_id'],
                    'goods_id' => $orderInfo['goods_id'],
                    'order_id' => $orderInfo['id'],
                    'province_id' => $orderInfo['goods']['province_id'],
                    'city_id' => $orderInfo['goods']['city_id'],
                    'region_id' => $orderInfo['goods']['region_id'],
                    'name' => $orderInfo['goods']['name'],
                    'price' => $orderInfo['goods']['price'],
                    'cover_img' => $orderInfo['goods']['cover_img'],
                    'cycle' => $orderInfo['goods']['cycle'],
                    'start_time' => $orderInfo['goods']['start_time'],
                    'quantity' => $orderInfo['quantity'],
                ]);
            }

            // 更新订单状态、更新支付状态 主订单、子订单
            $this->getOrderService($orderType)->updateOrderStatus($orderInfo['order_master_id']);
        });
    }
}
